<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class UserAddress extends Model
{
    use SoftDeletes;

    protected $table = 'user_address';

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];

    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];


    /**
     * 从用户提交的信息获取地址数据
     *
     * @return bool
     */
    public static function userAddressStore($param = ''){

        if($param){
            $address_region = $param['address_region'];
            $region_code = '';
            if($address = self::where('user_id',$param['user_id']) -> first()){


                foreach($address_region as $k=>$v){
                    if($k == 0){
                        $address ->prov    = $address_region[$k]['id'];
                    }else if($k == 1){
                        $address ->city    = $address_region[$k]['id'];
                    }else if($k == 2){
                        $address ->country = $address_region[$k]['id'];
                    }else if($k == 3){
                        $address ->town    = $address_region[$k]['id'];
                        $region_code       = $address ->town;
                    }else if($k == 4){
                        $address ->village = $address_region[$k]['id'];
                    }
                }
                $res = $address -> save();
            }else{

                foreach($address_region as $k=>$v){
                    if($k == 0){
                        $param['prov']    = $address_region[$k]['id'];
                    }else if($k == 1){
                        $param['city']    = $address_region[$k]['id'];
                    }else if($k == 2){
                        $param['country'] = $address_region[$k]['id'];
                    }else if($k == 3){
                        $param['town']    = $address_region[$k]['id'];
                        $region_code      = $param['town'];
                    }else if($k == 4){
                        $param['village'] = $address_region[$k]['id'];
                    }
                }

                $res = self::create($param);
            }

            if($res){
                User::where('id',$param['user_id']) -> update(['region_code' => $region_code]);
            }
            return $res;
        }

        return false;
    }
}
